"use client";

import React from "react";
import { type ColumnDef } from "@tanstack/react-table";
import { type CveItem } from "~/types/cveTypes";
import {
  type VulnerabilityWithSource,
  type SourceAttribution,
} from "~/types/scanTypes";
import { cn } from "~/components/lib/utils";
import {
  ExternalLink,
  BarChart4,
  Eye,
  Clock,
  Shield,
  Users,
} from "lucide-react";

export interface VulnTableData {
  cve: string;
  severity: "CRITICAL" | "HIGH" | "MEDIUM" | "LOW" | "INFORMATIONAL";
  description: string;
  riskScore: number;
  references: string[];
  affectedHosts: string[];
  sources?: string[];
  selected?: boolean;
}

// Enhanced vulnerability table data with source attribution
export interface VulnTableDataWithSources extends VulnTableData {
  sources: SourceAttribution[];
  port?: number;
  service_info?: string;
  first_detected?: string;
  last_confirmed?: string;
  confidence_score?: number;
}

// Utility function to render a severity badge
const SeverityBadge = ({ severity }: { severity: string }) => {
  const colorMap: Record<string, { bg: string; text: string }> = {
    CRITICAL: {
      bg: "bg-red-100 dark:bg-red-900/20",
      text: "text-red-800 dark:text-red-300",
    },
    HIGH: {
      bg: "bg-orange-100 dark:bg-orange-900/20",
      text: "text-orange-800 dark:text-orange-300",
    },
    MEDIUM: {
      bg: "bg-yellow-100 dark:bg-yellow-900/20",
      text: "text-yellow-800 dark:text-yellow-300",
    },
    LOW: {
      bg: "bg-green-100 dark:bg-green-900/20",
      text: "text-green-800 dark:text-green-300",
    },
    INFORMATIONAL: {
      bg: "bg-blue-100 dark:bg-blue-900/20",
      text: "text-blue-800 dark:text-blue-300",
    },
  };

  const config = colorMap[severity] || colorMap.INFORMATIONAL;

  return (
    <div className={cn("rounded-full px-2.5 py-0.5 text-center", config.bg)}>
      <span className={cn("text-xs font-medium", config.text)}>
        {severity.charAt(0).toUpperCase() + severity.slice(1).toLowerCase()}
      </span>
    </div>
  );
};

// Source badge component
const SourceBadge = ({ source }: { source: string }) => {
  const getSourceColor = (source: string) => {
    switch (source.toLowerCase()) {
      case "nmap":
        return "bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-300";
      case "agent":
        return "bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-300";
      case "rustscan":
        return "bg-orange-100 text-orange-800 dark:bg-orange-900/20 dark:text-orange-300";
      case "manual":
        return "bg-purple-100 text-purple-800 dark:bg-purple-900/20 dark:text-purple-300";
      default:
        return "bg-gray-100 text-gray-800 dark:bg-gray-900/20 dark:text-gray-300";
    }
  };

  return (
    <span
      className={cn(
        "inline-flex items-center rounded-full px-2 py-1 text-xs font-medium",
        getSourceColor(source)
      )}
    >
      {source}
    </span>
  );
};

// Column definitions
export const columns: ColumnDef<VulnTableData>[] = [
  {
    accessorKey: "severity",
    header: "Severity",
    cell: ({ row }) => {
      const severity = row.getValue("severity") as string;
      let bgColor = "";
      let textColor = "";

      switch (severity) {
        case "CRITICAL":
          bgColor = "bg-red-100 dark:bg-red-900/20";
          textColor = "text-red-800 dark:text-red-300";
          break;
        case "HIGH":
          bgColor = "bg-orange-100 dark:bg-orange-900/20";
          textColor = "text-orange-800 dark:text-orange-300";
          break;
        case "MEDIUM":
          bgColor = "bg-yellow-100 dark:bg-yellow-900/20";
          textColor = "text-yellow-800 dark:text-yellow-300";
          break;
        case "LOW":
          bgColor = "bg-green-100 dark:bg-green-900/20";
          textColor = "text-green-800 dark:text-green-300";
          break;
        case "INFORMATIONAL":
          bgColor = "bg-blue-100 dark:bg-blue-900/20";
          textColor = "text-blue-800 dark:text-blue-300";
          break;
      }

      return (
        <div
          className={cn(
            "inline-flex rounded-full px-2 py-1 text-xs font-medium",
            bgColor,
            textColor
          )}
        >
          {severity.charAt(0) + severity.slice(1).toLowerCase()}
        </div>
      );
    },
  },
  {
    accessorKey: "cve",
    header: "CVE ID",
    cell: ({ row }) => (
      <span className="font-mono text-xs font-medium">
        {row.getValue("cve")}
      </span>
    ),
  },
  {
    accessorKey: "riskScore",
    header: "Risk Score",
    cell: ({ row }) => {
      const score = parseFloat(row.getValue("riskScore"));
      let color = "bg-blue-500";
      if (score >= 9.0) color = "bg-red-500";
      else if (score >= 7.0) color = "bg-orange-500";
      else if (score >= 4.0) color = "bg-yellow-500";
      else if (score > 0) color = "bg-green-500";

      return (
        <div className="flex items-center">
          <div className="mr-2 text-xs font-medium">{score.toFixed(1)}</div>
          <div className="h-1.5 w-12 rounded-full bg-gray-200 dark:bg-gray-700">
            <div
              className={`h-1.5 rounded-full ${color}`}
              style={{ width: `${Math.min(score * 10, 100)}%` }}
            ></div>
          </div>
        </div>
      );
    },
  },
  {
    accessorKey: "description",
    header: "Description",
    cell: ({ row }) => {
      const description = row.getValue("description") as string;
      return (
        <div className="max-w-[500px] text-xs text-gray-900 dark:text-gray-100">
          <div className="line-clamp-2">{description}</div>
        </div>
      );
    },
  },
  {
    accessorKey: "affectedHosts",
    header: "Hosts",
    cell: ({ row }) => {
      const hosts = row.getValue("affectedHosts") as string[];
      return (
        <div className="text-center">
          <span className="text-xs font-medium text-gray-900 dark:text-gray-100">
            {hosts.length}
          </span>
        </div>
      );
    },
  },
  {
    id: "actions",
    cell: ({ row }) => {
      const cve = row.getValue("cve") as string;
      return (
        <div className="flex justify-end gap-2">
          <button
            onClick={(e) => {
              e.stopPropagation();
              // The parent will need to implement the view details handler
            }}
            className="rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-violet-600 dark:hover:bg-gray-700 dark:hover:text-violet-400"
            title="View vulnerability details"
          >
            <Eye className="h-4 w-4" />
          </button>
          <a
            href={`https://nvd.nist.gov/vuln/detail/${cve}`}
            target="_blank"
            rel="noopener noreferrer"
            className="rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-blue-600 dark:hover:bg-gray-700 dark:hover:text-blue-400"
            title="View in NVD database"
            onClick={(e) => e.stopPropagation()}
          >
            <ExternalLink className="h-4 w-4" />
          </a>
        </div>
      );
    },
  },
];
